//
//  TGUploadImgTool.m
//  TongGuanLease
//
//  Created by 张奇 on 2022/5/27.
//

#import "TGUploadImgTool.h"
#import "TGUrlInfoModel.h"
#import "ZLPhotoBrowser.h"

@interface TGUploadImgTool ()
@property (nonatomic, strong) NSMutableArray *listOfDownLoadImageArr;
@property (nonatomic, assign) NSInteger allCount;
@property (nonatomic, copy) UploadImgComplemention complementionBlock;
@property (nonatomic, strong) NSMutableArray <TGUrlInfoModel *>*resultUrlInfoArray;
@property (nonatomic, copy) NSString *filePath;
@end

@implementation TGUploadImgTool


- (void)uploadImgWithFilePath:(NSString *)filePath imgArray:(NSArray <UIImage*>*)imgArray complemention:(UploadImgComplemention)complemention {
    
    self.listOfDownLoadImageArr = [NSMutableArray arrayWithArray:imgArray];
    self.allCount = imgArray.count;
    self.complementionBlock = complemention;
    self.resultUrlInfoArray = [NSMutableArray array];
    self.filePath = filePath;
    [self begainUpload];
}

- (void)begainUpload {
    
    if (self.listOfDownLoadImageArr.count > 0) {
        id firstImg = self.listOfDownLoadImageArr.firstObject;

        UIImage *image = nil;
        if ([firstImg isKindOfClass:[NSString class]]) {
            // 通过url取得图片
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:firstImg]];
            image = [UIImage imageWithData:data];
            // 直接就是图片
        } else if ([firstImg isKindOfClass:[UIImage class]]) {
            image = firstImg;
        }
       
        [TGNetworkManager uploadImage:image filePath:self.filePath success:^(TGResponseItem *responseItem) {
            if (responseItem.success) {
                TGUrlInfoModel *urlInfoModel = [TGUrlInfoModel modelWithJSON:responseItem.data];
                [self.resultUrlInfoArray addObject:urlInfoModel];
                [self.listOfDownLoadImageArr removeObjectAtIndex:0];
                NSString *pStr = [NSString stringWithFormat:@"%zd/%zd", (long)(self.allCount-self.listOfDownLoadImageArr.count), (long)self.allCount];
                self.complementionBlock(pStr, nil, NO, nil);
                [self begainUpload];
            } else {
                self.complementionBlock(@"", [NSError new], YES, nil);
            }
        } failure:^(NSError *error) {
            self.complementionBlock(@"", error, YES, nil);
        }];
 
    } else {
        self.complementionBlock(@"完成", nil, YES, self.resultUrlInfoArray);
    }
}


@end
